package com.proton.carepatchtemp.utils.net;

import android.text.TextUtils;

import com.android.volley.Response;
import com.apkfuns.logutils.LogUtils;
import com.google.gson.reflect.TypeToken;
import com.proton.carepatchtemp.application.VCare;
import com.proton.carepatchtemp.constant.Codes;
import com.proton.carepatchtemp.constant.Extras;
import com.proton.carepatchtemp.database.daomanager.DeviceManager;
import com.proton.carepatchtemp.database.table.Device;
import com.proton.carepatchtemp.database.table.FirmWare;
import com.proton.carepatchtemp.database.table.ShareHistory;
import com.proton.carepatchtemp.utils.FileUtils;
import com.proton.carepatchtemp.utils.JSONUtils;
import com.proton.carepatchtemp.utils.ThreadUtils;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;
import com.proton.carepatchtemp.utils.net.pair.ParamPair;
import com.proton.carepatchtemp.utils.net.pair.ResultPair;
import com.proton.carepatchtemp.utils.net.request.JGet;
import com.proton.carepatchtemp.utils.net.request.JPost;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by Api on 2016/10/14.
 */

public class DeviceCenter extends DataCenter {
    public static final String add = "/device/add";
    public static final String delete = "/device/delete";
    public static final String getList = "/device/getlist";
    public static final String getShareHistory = "/device/get";
    public static final String shareDevice = "/tempdevice/share";
    public static final String cancleShare = "/device/canceltempshare";
    private static final String getFirmWare = "/user/getTEMPPackage";
    private static final String updateByBtAddress = "/user/updateByBtaddress";

    public static boolean updateByBtaddress(String macAddress, String version) {
        if (DataCenter.noNet()) {
            return false;
        }

        List params = new ArrayList();
        params.add(new ParamPair(Extras.BLUETOOTH_ADDRESS, macAddress));
        params.add(new ParamPair(Extras.DEVICE_FIRMWARE_VERSION, version));
        VolleyUtil.addRequest(new JPost(getApi(updateByBtAddress), params, new Response.Listener<ResultPair>() {
            @Override
            public void onResponse(ResultPair response) {
                String ret = response.getName();
                String msg = response.getValue();
                EventBus.getDefault().post(new MainEvent(Codes.DEVICE_UPDATE_SUCCEED));
                LogUtils.d(response);
            }
        }));
        return false;
    }

    public static boolean getUpdateFirmWare(String version) {
        if (DataCenter.noNet()) {
            return false;
        }
        List params = new ArrayList();
        params.add(new ParamPair(Extras.DEVICE_UPDATE_KEY, version));
        VolleyUtil.addRequest(new JPost(getApi(getFirmWare), params, new Response.Listener<ResultPair>() {

            @Override
            public void onResponse(ResultPair response) {
                String ret = response.getName();
                String msg = response.getValue();
                if (response.isSuccess()) {
                    FirmWare firmWare = JSONUtils.getObj(msg, FirmWare.class, "yyyy-MM-dd");
                    if (null != firmWare) {
                        VCare.get().setFirmWare(firmWare);
                        ThreadUtils.runOnOtherThread(() -> {
                            File file = new File(FileUtils.firmWare + File.separator + firmWare.getVersion());
                            if (!file.exists()) {
                                FileUtils.downLoadFromUrl(firmWare.getLoadAdress(), firmWare.getVersion(), FileUtils.firmWare);
                            }
                        });
                    }
                }
            }
        }));
        return false;
    }

    public static boolean add(Device mDevice) {
        if (DataCenter.noNet()) {
            return false;
        }
        List params = new ArrayList<>();
        params.add(new ParamPair(Extras.TYPE, mDevice.getType()));
        params.add(new ParamPair(Extras.SN, mDevice.getSn()));
        params.add(new ParamPair(Extras.NAME, mDevice.getName()));
        params.add(new ParamPair(Extras.BLUETOOTH_ADDRESS, mDevice.getBtaddress()));
        params.add(new ParamPair(Extras.DEVICE_FIRMWARE_VERSION, mDevice.getVersion()));
//        LogUtils.e(params);
        VolleyUtil.addRequest(new JPost(getApi(add), params, new Response.Listener<ResultPair>() {

            @Override
            public void onResponse(ResultPair response) {
                String ret = response.getName();
                String msg = response.getValue();
                if (response.isSuccess()) {
                    // TODO: 2016/10/30 插入数据库
                    Device dvc = JSONUtils.getObj(msg, Device.class, "yyyy-MM-dd");
                    DeviceManager.insertOrReplace(dvc);
                    EventBus.getDefault().post(new MainEvent(Codes.ADD_DEVICE, ret, mDevice.getBtaddress(), dvc));
//                    VCare.getACacheInstance().put(Extras.ACHCHE_DEVICE,dvc);
                } else {
                    EventBus.getDefault().post(new MainEvent(Codes.ADD_DEVICE, ret, msg));
                }

                LogUtils.d(msg);

            }
        }));
        return false;
    }

    public static boolean delete(String deviceId) {
        if (DataCenter.noNet()) {
            return false;
        }
        List params = new ArrayList<>();
        params.add(new ParamPair(Extras.DEVICE_ID, deviceId));

        VolleyUtil.addRequest(new JPost(getApi(delete), params, new Response.Listener<ResultPair>() {

            @Override
            public void onResponse(ResultPair response) {
                String ret = response.getName();
                String msg = response.getValue();
                if (response.isSuccess()) {
                    //数据库删除
                    DeviceManager.deleteDevice(Long.valueOf(deviceId));
                }
                EventBus.getDefault().post(new MainEvent(Codes.DEVICE_DELETE, ret, msg));
            }
        }));
        return false;
    }

    public static boolean getList() {
        if (DataCenter.noNet()) {
            return false;
        }
        List params = new ArrayList<>();
        VolleyUtil.addRequest(new JGet(getApi(getList), params, new Response.Listener<ResultPair>() {

            @Override
            public void onResponse(ResultPair response) {
                String ret = response.getName();
                String msg = response.getValue();
                Type listType = new TypeToken<ArrayList<Device>>() {
                }.getType();
                List<Device> devices = JSONUtils.getObj(msg, listType, "yyyy-MM-dd");
                List<Device> tempDevices = new ArrayList<Device>();
//                LogUtils.d(response);
                if (response.isSuccess()) {
                    for (Device device :
                            devices) {
                        if (Extras.DVC_TYPE_TMP == device.getType() && device.getCreator() == VCare.get().getUid()) {
                            tempDevices.add(device);
                        }
                    }
                }
                LogUtils.d(tempDevices);
                //数据库保存
                DeviceManager.insertOrReplaceInTx(tempDevices);
                if (null != VCare.get().getFirmWare()) {
                    ThreadUtils.runOnOtherThread(() -> {
                        int needUpdate = 0;
                        for (Device device :
                                tempDevices) {
                            //V1.0.1和V1.0.1不支持固件升级
                            if (!TextUtils.isEmpty(device.getVersion()) &&
                                    !device.getVersion().equalsIgnoreCase("V1.0.0") &&
                                    !device.getVersion().equalsIgnoreCase("V1.0.1") &&
                                    !device.getVersion().equalsIgnoreCase(VCare.get().getFirmWare().getVersion()) &&
                                    device.getSn().compareTo("11A17030000") > 0) {
                                needUpdate += 1;

                            }
                        }
                        VCare.get().needUpdate = needUpdate;
                    });

                }

                EventBus.getDefault().post(new MainEvent(Codes.DEVICE_GET_LIST, ret, devices));
            }
        }));
        return false;
    }

    public static boolean share(String deviceId, String mobile, long profileId) {
        if (DataCenter.noNet()) {
            return false;
        }
        List params = new ArrayList<>();
        params.add(new ParamPair(Extras.DEVICE_ID, deviceId));
        params.add(new ParamPair(Extras.MOBILE, mobile));
        params.add(new ParamPair(Extras.PRF_PROFILEID, profileId));
        VolleyUtil.addRequest(new JPost(getApi(shareDevice), params, new Response.Listener<ResultPair>() {

            @Override
            public void onResponse(ResultPair response) {
                String ret = response.getName();
                String msg = response.getValue();

                LogUtils.e(response);
                JSONObject jsonObject = JSONUtils.getJOSNObj(msg);
                try {
                    if (null != jsonObject) {
                        msg = jsonObject.getString("data");
                    } else {
                        msg = "";
                    }
                } catch (JSONException e) {
                    LogUtils.e(e);
                    msg = "";
                }
                if (response.isSuccess()) {
                    EventBus.getDefault().post(new MainEvent(Codes.DEVICE_SHARE, ret, msg));
                    getShareHistory(deviceId);
                } else {
                    EventBus.getDefault().post(new MainEvent(Codes.DEVICE_SHARE, ret, msg));
                }
            }
        }));
        return false;
    }

    public static boolean cancleShare(long shareId, long profileId) {
        if (DataCenter.noNet()) {
            return false;
        }
        List params = new ArrayList<>();
        params.add(new ParamPair(Extras.SHARE_SHARE_ID, shareId));
        params.add(new ParamPair(Extras.PRF_PROFILEID, profileId));
        LogUtils.e("shareid" + shareId);
        LogUtils.e("profileid" + profileId);
        VolleyUtil.addRequest(new JPost(getApi(cancleShare), params, new Response.Listener<ResultPair>() {

            @Override
            public void onResponse(ResultPair response) {
                String ret = response.getName();
                String msg = response.getValue();

//                Device device = JSONUtils.getObj(msg, Device.class, "yyyy-MM-dd");

                LogUtils.e(msg + ret);
                if (response.isSuccess()) {
//                    LogUtils.e(device);
                    EventBus.getDefault().post(new MainEvent(profileId + "", Codes.DEVICE_CANCLE_SHARE, ret, msg, shareId));
                } else {
                    EventBus.getDefault().post(new MainEvent(profileId + "", Codes.DEVICE_CANCLE_SHARE, ret, msg, shareId));
                }
            }
        }));
        return false;
    }

    public static boolean getShareHistory(String deviceId) {
        if (DataCenter.noNet()) {
            return false;
        }
        List params = new ArrayList<>();
        params.add(new ParamPair(Extras.DEVICE_ID, deviceId));

        VolleyUtil.addRequest(new JGet(getApi(getShareHistory), params, new Response.Listener<ResultPair>() {

            @Override
            public void onResponse(ResultPair response) {
                String ret = response.getName();
                String msg = response.getValue();

                ShareHistory shareHistory = JSONUtils.getObj(msg, ShareHistory.class);
                if (response.isSuccess()) {
                    if (null != shareHistory) {
                        EventBus.getDefault().post(new MainEvent(shareHistory.getBtaddress(), Codes.DEVICE_SHARE_HISTORY, ret, msg, shareHistory));
                    }
                    LogUtils.d(response);
                } else {
                    EventBus.getDefault().post(new MainEvent(Codes.DEVICE_SHARE_HISTORY, ret, msg));
                }

            }
        }));
        return false;
    }

}
